<?php

namespace App\Http\Controllers\Guard\Repair;

use App\Http\Controllers\Common\GuardController;
use App\Models\Common\China;
use App\Models\Repair\ReapirFactoryComment;
use App\Models\Repair\RepairFactory;
use App\Models\Repair\RepairFactoryAdmin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class RepairFactoryController extends GuardController
{
    public function index(Request $request) {
        $conditions = $request->input();
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',15);
        $records = (new RepairFactory())->getLst($conditions)->with('getAdmin')->paginate($pageSize,$this->getCol,'page',$page);

        $mapArea = China::getMap();

        foreach ($records as $record) {
            $record->business_time = $record->business_s_time.'-'.$record->business_e_time;
            $record->detail_address = $mapArea[$record->prov_code];
            if($record->prov_code!=$record->city_code){
                $record->detail_address .= $mapArea[$record->city_code];
            }
            $record->detail_address .= $mapArea[$record->county_code];
            $record->detail_address .= $record->address;
            $record->call_phone = $record->getAdmin->pluck('phone')->implode(',');

        }
        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {
        $id = $request->input('id',0);
        $info = $request->input();
        if($request->has('status') && count($info)<=2){
            RepairFactory::updateOrCreate(compact('id'),['status'=>$request->input('status')]);
            return responseSuccess();
        }

        if(isset($info['prov_code']))unset($info['prov_code']);
        if(isset($info['city_code']))unset($info['city_code']);
        if(isset($info['county_code']))unset($info['county_code']);
        if(isset($info['prov_name']))unset($info['prov_name']);
        if(isset($info['city_name']))unset($info['city_name']);
        if(isset($info['county_name']))unset($info['county_name']);
        if(isset($info['status']))unset($info['status']);

        $this->validate($request, [
            'name'=>'required',
            'address'=>'required',
            'lng'=>'required',
            'lat'=>'required',
            'introduce'=>'required',
            //'imgs'=>'required',
        ],[],[
            'name'=>'维修厂名称',
            'call_phone'=>'联系电话',
            'lng'=>'经度',
            'lat'=>'纬度',
            'introduce'=>'介绍',
            'imgs'=>'图片',
        ]);



        $info['prov_code'] = array_shift($info['selectArea']);
        $info['city_code'] = array_shift($info['selectArea']);
        $info['county_code'] = array_shift($info['selectArea']);
        unset($info['selectArea']);

        $info['imgs'] = implode(",", array_column($info['imgs'], 'path'));

        Str::replace('，', ',', $info['call_phone']);
        $call_phone = $info['call_phone'];

        unset($info['call_phone']);
        if(isset($info['get_admin']))unset($info['get_admin']);


        try{
            DB::beginTransaction();
            $factory = RepairFactory::updateOrCreate(compact('id'),$info);
            $phones = explode(',', $call_phone);


            RepairFactoryAdmin::where(['factory_id'=>$factory->id])->forceDelete();
            foreach ($phones as $phone) {
                RepairFactoryAdmin::create(['factory_id'=>$factory->id,'phone'=>$phone]);

            }

            DB::commit();
            return responseSuccess();
        }catch(\Exception $e){
            DB::rollback();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }


    }

    public function detail(Request $request) {
        $id = $request->input('id',0);
        $record = RepairFactory::where(compact('id'))->first();

        $mapArea = China::getMap();

        $record->prov_name = $mapArea[$record->prov_code];
        $record->city_name = $mapArea[$record->city_code];
        $record->county_name = $mapArea[$record->county_code];

        $imgs = array_filter(explode(',', $record->imgs));
        $temp = [];
        foreach ($imgs as $img){
            $temp[] = [
                //'name'=>'图片',
                //'url'=>$img,
                'uid'=>uniqid(),
                'path'=>$img,
                'url'=>asset($img)
            ];
        }
        $record->imgs = $temp;

        $record->call_phone = RepairFactoryAdmin::where('factory_id',$id)->pluck('phone')->implode(',');


        return responseSuccess($record->toArray());
    }

    public function del(Request $request) {
        $id = $request->input('ids',0);
        return $this->delRecords(RepairFactory::class, $id);
    }

    public function commentLst(Request $request) {
        $page = $request->input('page',1);
        $name = $request->input('name');
        $pageSize = $request->input('pageSize',15);
        $records = (new ReapirFactoryComment())->getLst()
            ->with(['getUser','getFactory']);
        if(!empty($name)){
            $records = $records->whereHas('getFactory', function ($q) use ($name) {
                $q->where('name','like',"%$name%");
            });
        }

        $records = $records->paginate($pageSize,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());
    }

    public function commentDel(Request $request) {
        $id = $request->input('ids',0);
        ReapirFactoryComment::where(compact('id'))->delete();
        return responseSuccess();
    }
}
